﻿
$(function () {
    toastr.options.positionClass = 'toast-bottom-center';

    // 最大人数验证
    var checkMaxCount = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('请填写最大检查人数'))
        }
        if (!Number.isInteger(Number(value))) {
            return callback(new Error('必须为整数'));
        }
        callback();
    };

    var vm = new Vue({
        el: '#app',
        data: {
            // 角色与权限

            // 特殊排班权限
            scheduleOverridePermission: true, // 能进到本页面，就是true
            createPermission: false,
            editPermission: false,
            deletePermission: false,
            disablePermission: false,

            //号池权限
            poolPermission: true,  // 能进到页面就是true
            poolCreatePermission: false,
            poolDeletePermission: false,
            poolEditPermission: false,



            multiDepartmentPermission: false,

            // 主页面
            filterDate: null,
            dialogVisible: false, // 创建用户对话框，是否显示
            dialogTitle: '新建特殊排班',
            actionType: '新建',
            tableData: [],
            formLabelWidth: '80px',
            department: null,   // 当前科室
            deviceType: null,   // 当前设备类型
            device: null,       // 当前设备
            treeData: [],
            selectedSO: null,    // 当前选中的特殊排班

            scheduleOverride: {
                id: null,
                date: null,
                deviceId: null
            },

            pools: [],  // 特殊计划号池
            selectedPools: [],  // 被选中的号池
            pool: {     // 号池对象
                id: null,
                date: null,
                startTime: null,
                endTime: null,
                deviceId: null,
                maxCount: null,
                allowOverFlow: null,
                isActive: null,
                scheduleOverrideId: null
            },
            poolTotal: 0,
            poolPage: 1,
            poolPageSize: 10,

            poolDialogVisible: false,
            poolDialogTitle: '',
            poolActionType: '',
            poolLabelWidth: '80px',

            batchDialogVisible: false,
            batchDialogTitle: '批量生成号池',
            batchPoolModel: {
                startTime: null,
                endTime: null,
                interval: 30,
                maxCount: 10,
                allowOverFlow: true,
                date: null,
                options: [
                    {
                        label: 30,
                        value:30
                    },
                    {
                        lable: 60,
                        value:60
                    }
                ]
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },

            // 特殊排班对话框
            pickerOptions: {
                disabledDate(time) {
                    const today = new Date();
                    const tomorrow = new Date(today);
                    tomorrow.setDate(tomorrow.getDate() + 1);// 明天
                    return time.setHours(0, 0, 0, 0) <= today.setHours(0, 0, 0, 0);

                }
            },

            // 值格式-- 特殊号池对话框
            valueFormat: 'HH:mm',
            timePickerFormat: 'HH:mm a',

            defaultPickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },

            // 号池详情对话框
            startPickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },

            // 号池详情对话框
            endPickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },

            // (开始时间) 特殊号池对话框
            startTimePickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },

            // （结束时间）特殊号池对话框
            endTimePickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },



            // 验证规则
            rules: {
                date: [
                    { required: true, message: '请选择日期', trigger: 'blur' }
                ]
            },

            poolRules: {
                startTime: [
                    { required: true, message: '请输入开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, message: '请输入结束时间', trigger: 'blur' }
                ],
                maxCount: [
                    { required: true, message: '请输入最大数量', trigger: 'blur' },
                    { validator: checkMaxCount, trigger: 'blur' }
                ]
            }
        },
        computed: {
            tableShow: function () {
                var vm = this;
                if ((vm.treeData[0] && vm.treeData[0].children.length > 0) || vm.department) {
                    return true;
                }
                return false;
            }
        },
        methods: {
            // 号池对话框
            startChange(val) {
                var vm = this;
                var str = `${val}:00 - 23:59:59`
                vm.endPickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 号池对话框
            endChange(val) {
                var vm = this;
                var str = `00:00:00 - ${val}:59`
                vm.startTimePickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 结束时间改变(号池对话框)
            endTimeChange(val) {
                var vm = this;
                var str = `00:00:00 - ${val}:59`
                vm.startTimePickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 开始时间改变（号池对话框）
            startTimeChange(val) {
                var vm = this;
                var str = `${val}:00 - 23:59:59`
                vm.endTimePickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 号池表分页
            currentPageChange(val) {
                var vm = this;
                vm.poolPage = val;
                vm.loadPoolList();
            },

            //  号池表分页 
            pageSizeChange(val) {
                var vm = this;
                vm.poolPageSize = val;
                vm.loadPoolList();
            },

            // 特殊排班表，当前行改变
            currentRowChange(row) {
                var vm = this;
                vm.selectedSO = row;
                vm.poolPage = 1;
                vm.loadPoolList();
            },

            // 加载表格数据(只在初始化时执行一次)
            loadTableData() {
                var vm = this;
                return new Promise(resolve => {
                    if (vm.multiDepartmentPermission && vm.treeData[0].children.length > 0) { // admin 角色下，有科室
                        vm.department = vm.treeData[0].children[0]; // 默认加载tree中的第一个科室的用户情况
                        vm.loadsList();
                    }
                    else if (vm.multiDepartmentPermission && vm.treeData[0].children.length === 0) { // admin角色下，系统中还没创建任何科室
                        // 提示系统还没有任何科室
                    }
                    else if (!vm.multiDepartmentPermission) { // 必然时是科室用户，而且必然是已经登录了某个科室，而且已经加载了科室
                        // 根据登录科室加载
                        vm.loadsList();
                    }
                    resolve();
                })
            },

            // 加载设备特殊排班
            loadsList() {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'GET',
                        url: `/api/schedule-override/get-list?deviceId=${vm.device.id}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.tableData = res.data;
                            if (res.data.length > 0) {
                                vm.selectedSO = vm.tableData[0];
                                vm.$refs['so-table'].setCurrentRow(vm.tableData[0]);
                                vm.loadPoolList();
                            }
                            else {
                                vm.selectedSO = null;
                                vm.pools = [];
                            }
                        }
                    });
                })
            },

            // 获取特殊排班计划下号池列表(分页)
            loadPoolList() {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/pool/load-pool-list?sid=${vm.selectedSO.id}&page=${vm.poolPage}&pageSize=${vm.poolPageSize}`
                }).then(res => {
                    if (res.code === 0) {
                        vm.pools = res.data.list;
                        vm.poolTotal = res.data.total;
                    }
                });
            },

            // 判断给定日期下是否存在
            isAlreadyExist(deviceId, date) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/schedule-override/is-already-exist?deviceId=${deviceId}&date=${date}`
                    }).then(res => {
                        if (res.code === 0) {
                            if (res.data.exist) {
                                abp.message.confirm(`${date}下已经存在特殊排班，如果保存将覆盖原排班`)
                                    .then(confirmed => {
                                        if (confirmed) {
                                            resolve(true);
                                        }
                                        else {
                                            resolve(fasle);
                                        }
                                    })
                            }
                            resolve(true);
                        }
                    })
                });
            },

            // 显示新建对话框
            showCreate() {
                var vm = this;
                vm.dialogTitle = '新建特殊排班';
                vm.actionType = '新建';
                vm.dialogVisible = true;
                vm.scheduleOverride.deviceId = vm.device.id;
            },



            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        vm.isAlreadyExist(vm.scheduleOverride.deviceId, vm.scheduleOverride.date).then(res => {
                            if (res) {
                                vm.scheduleOverride.deviceId = vm.device.id;
                                abp.ajax({
                                    type: 'post',
                                    url: `/api/schedule-override/submit-create`,
                                    data: JSON.stringify(vm.scheduleOverride)
                                }).then(res => {
                                    if (res.code == 0) {
                                        vm.resetForm();
                                        vm.loadsList();
                                        abp.notify.success(res.msg);
                                    }
                                });
                            }
                        })
                    }
                });

            },


            // 删除特殊排班
            deleteSingle(id) {
                var vm = this;
                abp.message.confirm('删除检查项目/目录(包含其所有子级)')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/schedule-override/delete?id=${id}`
                            }).then((res) => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadsList()
                                    vm.pools = [];
                                }
                            })
                        }
                    });
            },

            // 号池选中改变(多选)
            poolSelectionChange(val) {
                var vm = this;
                vm.selectedPools = val;
            },

            // 打开创建号池对话框
            showCreatePool() {
                var vm = this;
                if (vm.selectedSO) {
                    vm.poolDialogTitle = "创建号池";
                    vm.poolActionType = "新建";
                    vm.pool.date = vm.selectedSO.date;
                    vm.pool.deviceId = vm.device.id;
                    vm.pool.isActive = true;
                    vm.pool.maxCount = 10;
                    vm.pool.allowOverFlow = true;
                    vm.pool.scheduleOverrideId = vm.selectedSO.id;
                    vm.poolDialogVisible = true;
                } else {
                    abp.notify.error('无选中特殊排班！');
                }
            },

            // 打开号池编辑
            showEditPool(id) {
                var vm = this;
                abp.ajax({
                    type: 'get',
                    url: `/api/pool/get?id=${id}`
                }).then(res => {
                    if (res.code === 0) {
                        debugger;
                        vm.pool = res.data;
                        vm.pool.startTime = vm.pool.startTimeStr;
                        vm.pool.endTime = vm.pool.endTimeStr;
                        vm.poolActionType = "编辑";
                        vm.pool.date = vm.selectedSO.date;
                        vm.pool.deviceId = vm.device.id;
                        vm.scheduleOverrideId = vm.selectedSO.id;
                        vm.poolDialogVisible = true;
                    }
                })
            },



            // 保存号池
            savePool() {
                var vm = this;
                debugger;
                if (vm.poolActionType === '新建') {
                    vm.submitPoolCreate();
                }
                else {
                    vm.submitPoolEdit();
                }
            },

            // 提交新建号池
            submitPoolCreate() {
                var vm = this;
                vm.$refs['poolDialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: '/api/pool/submit-create',
                            data: JSON.stringify(vm.pool)
                        }).then(res => {
                            if (res.code === 0) {
                                vm.resetPoolForm();
                                vm.poolDialogVisible = false;
                                vm.loadPoolList();
                            }
                        });
                    }
                });
            },

            // 提交号池编辑
            submitPoolEdit() {
                var vm = this;
                vm.pool.scheduleOverrideId = vm.selectedSO.id;
                vm.$refs['poolDialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: '/api/pool/submit-edit',
                            data: JSON.stringify(vm.pool)
                        }).then(res => {
                            if (res.code === 0) {
                                vm.loadPoolList();
                                vm.resetPoolForm();
                            }
                        });
                    }
                })
            },

            // 启用禁用
            enbaleToggle(row) {
                var str = '';
                if (!row.isActive) {
                    str = '禁用号池，将号池将无法预约！';
                } else {
                    str = '启用号池，号池将开放预约';
                }
                abp.message.confirm(str)
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/pool/enable-toggle?id=${row.id}`
                            });
                        }
                    })
            },

            // 删除号池
            deletePool(id) {
                var vm = this;
                abp.message.confirm('删除号池')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'delete',
                                url: `/api/pool/delete?id=${id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadPoolList();
                                }
                            })
                        }
                    })
            },

            deletePoolMany() {
                var vm = this;
                if (vm.selectedPools.length === 0) {
                    abp.notify.error('请先选中要删除的号池！')
                } else {
                    var idList = vm.selectedPools.map(item => item.id);
                    abp.message.confirm('批量删除号池')
                        .then(confirmed => {
                            if (confirmed) {
                                abp.ajax({
                                    type: 'post',
                                    url: '/api/pool/delete-pool-many',
                                    data: JSON.stringify(idList)
                                }).then(res => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.loadPoolList();
                                    }
                                })
                            }
                        })
                }
            },

            // 批量生成号池对话框 
            showBatchCreate() {
                var vm = this;
                vm.batchPoolModel.startTime = null;
                vm.batchPoolModel.endTime = null;
                vm.batchPoolModel.maxCount = 10;
                vm.batchPoolModel.allowOverFlow = true;
                vm.batchPoolModel.interval = 30;
                vm.batchPoolModel.date = vm.selectedSO.date;
                vm.batchDialogVisible = true;
            },

            // 提交批量生成
            submitBatchCreate() {
                var vm = this;
                vm.$refs['batchDialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/pool/batch-create?sid=${vm.selectedSO.id}`,
                            data: JSON.stringify(vm.batchPoolModel)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadPoolList();
                                vm.resetBatchForm();
                            }
                        })
                    }
                });
            },

            // 加载科室（如果是科室用户时）
            loadDepartment() {
                return new Promise(resolve => {
                    if (!vm.multiDepartmentPermission) {
                        // 获取当前登录科室
                        abp.ajax({
                            type: "GET",
                            url: "/api/department-user/get-current-user-department"
                        }).then(res => {
                            vm.department = res;
                            resolve();
                        });
                    }
                    else {
                        resolve();
                    }
                });
            },

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                var vm = this;
                return new Promise(resolve => {
                    var url;
                    if (vm.multiDepartmentPermission) { // 如果有管理员角色（multiDepartmentPermission只在admin角色中才有）
                        url = `/api/schedule-override/get-tree-data?depId=${null}`
                    }
                    else {
                        url = `/api/schedule-override/get-tree-data?depId=${vm.department.id}`
                    }
                    abp.ajax({
                        type: "GET",
                        url: url
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            if (vm.treeData[0].children.length > 0) { // 有科室存在
                                res.data[0].children.forEach((department, index) => {
                                    if (!vm.device && department.children && department.children.length > 0) {
                                        vm.device = vm.treeData[0].children[index].children[0];
                                        vm.department = department;
                                    }
                                })
                            }
                            else {
                                vm.tableShow = false;
                            }
                            resolve();
                        }
                    });
                });
            },

            // 加载当前权限
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('AppointManagerGroup.ScheduleOverride')) {
                        vm.scheduleOverridePermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.ScheduleOverride.Create')) {
                            vm.createPermission = true;
                        }

                        if (abp.auth.isGranted('AppointManagerGroup.ScheduleOverride.Edit')) {
                            vm.editPermission = true;
                        }

                        if (abp.auth.isGranted('AppointManagerGroup.ScheduleOverride.Delete')) {
                            vm.deletePermission = true;
                        }

                        if (abp.auth.isGranted('AppointManagerGroup.ScheduleOverride.Disable')) {
                            vm.disablePermission = true;
                        }
                    }
                    if (abp.auth.isGranted('AppointManagerGroup.SpecialPool')) {
                        vm.poolPermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.SpecialPool.Create')) {
                            vm.poolCreatePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.SpecialPool.Delete')) {
                            vm.poolDeletePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.SpecialPool.Edit')) {
                            vm.poolEditPermission = true;
                        }
                    }

                    if (abp.auth.isGranted('OthersGoup.Others.MuMultiDepartment')) {
                        vm.multiDepartmentPermission = true;
                    }
                    resolve();
                });
            },

            // 点击树节点
            nodeClicked(node, obj, aa) {
                if (node.icon != 'fa fa-hospital' && node.icon != 'fa fa-building') {
                    var vm = this;
                    vm.device = node;
                    vm.department = obj.parent.data;
                    vm.poolPage = 1;
                    vm.loadsList();
                }
            },

            // 重置，特殊排班表单
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.scheduleOverride).forEach(key => {
                    vm.scheduleOverride[key] = null;
                });
            },

            // 重置，特殊号池表单
            resetPoolForm() {
                var vm = this;
                vm.$refs['poolDialogForm'].resetFields();
                vm.startPickerOption = vm.defaultPickerOption;
                vm.endPickerOption = vm.defaultPickerOption;
                vm.poolDialogVisible = false;
                Object.keys(vm.pool).forEach(key => {
                    vm.pool[key] = null;
                })

            },

            resetBatchForm() {
                var vm = this;
                vm.$refs['batchDialogForm'].resetFields();
                vm.batchDialogVisible = false;
                vm.startTimePickerOption = vm.defaultPickerOption;
                vm.endTimePickerOption = vm.defaultPickerOption;
                Object.keys(vm.batchPoolModel).forEach(key => {
                    vm.batchPoolModel[key] = null;
                })
            },

            // 初始化
            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadDepartment().then(() => {
                            vm.loadTreeData().then(() => {
                                vm.loadTableData();
                            });
                        })
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});